#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
配置管理器模块

提供用户配置的加载和保存功能
"""

import os
import json
import platform

class ConfigManager:
    """配置管理类"""
    
    def __init__(self):
        """初始化配置管理器"""
        self.config = {}
        self.config_dir = self._get_config_dir()
        self.config_file = os.path.join(self.config_dir, "config.json")
        
        # 确保配置目录存在
        os.makedirs(self.config_dir, exist_ok=True)
        
        # 加载配置
        self.load_config()
    
    def load_config(self):
        """从文件加载配置
        
        返回:
            dict: 配置数据字典
        """
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
        except Exception as e:
            pass
        return {}
    
    def save_config(self):
        """保存配置到文件
        
        返回:
            bool: 保存成功返回True，否则返回False
        """
        try:
            config_dir = os.path.dirname(self.config_file)
            if config_dir and not os.path.exists(config_dir):
                os.makedirs(config_dir, exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            return False
    
    def get_user_pref(self, key, default=None):
        """获取用户偏好设置
        
        参数:
            key (str): 设置键名
            default: 默认值
            
        返回:
            设置值或默认值
        """
        if key in self.config:
            return self.config[key]
        return default
    
    def set_user_pref(self, key, value):
        """设置用户偏好
        
        参数:
            key (str): 设置键名
            value: 设置值
            
        返回:
            bool: 设置成功返回True
        """
        self.config[key] = value
        return self.save_config()
    
    def _create_default_config(self):
        """创建默认配置
        
        返回:
            dict: 默认配置字典
        """
        return {
            "include_coordinates": True,
            "default_format": "PNG",
            "sensitivity": 20,
            "recent_files": [],
            "recent_dirs": [],
            "bg_color": [255, 255, 255],
            "bg_threshold": 30,
            "ui_theme": "default",
            "language": "zh_CN"
        }
    
    def _get_config_dir(self):
        """获取配置目录
        
        根据操作系统选择合适的配置目录
        
        返回:
            str: 配置目录路径
        """
        app_name = "ImageCutter"
        system = platform.system()
        
        if system == "Windows":
            # Windows: %APPDATA%\ImageCutter
            return os.path.join(os.getenv('APPDATA'), app_name)
        elif system == "Darwin":
            # macOS: ~/Library/Application Support/ImageCutter
            return os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', app_name)
        else:
            # Linux/其他: ~/.config/imagecutter
            return os.path.join(os.path.expanduser('~'), '.config', 'imagecutter')
            
    def reset_to_defaults(self):
        """重置为默认配置
        
        返回:
            bool: 操作成功返回True
        """
        self.config = self._create_default_config()
        return self.save_config() 